package com.blue.base.security.filters;

import com.blue.base.common.exception.AuthException;
import com.blue.base.security.api.AuthService;
import com.blue.base.security.config.SecurityAuthConfig;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 请求路径的权限校验[已登录]
 *
 * @author liulei
 * @version 1.0
 */
@Slf4j
@AllArgsConstructor
public class RequestPermissionRuleFilter extends OncePerRequestFilter {

    private AuthService authService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        String servletPath = request.getServletPath();
        logger.info("权限校验filter......");
        Collection<? extends GrantedAuthority> authorities = SecurityContextHolder.getContext().getAuthentication().getAuthorities();
        if (authorities.isEmpty()) {
            throw new AuthException(700, "未配置任何角色，请联系管理员");
        }
        List<String> roles = authorities.stream().map(au -> au.getAuthority()).collect(Collectors.toList());
        if (authService.hasRight(roles, servletPath)) {
            filterChain.doFilter(request, response);
            return;
        }
        throw new AuthException(700, "权限不足，无法访问");
    }
}
